var restify = require('restify')
var actions = require('./router.js')
var filters = require('./filters.js')

module.exports = {
  config: {
    // ip: '127.0.0.1',
    port: 10022,
    name: 'babyapi'
  },
  start: function () {
    var server = restify.createServer({
      name: this.config.name
    })
    filters.pres.forEach(function (func) {
      server.pre(func)
    })
    server.use(restify.plugins.queryParser())
    server.use(restify.plugins.bodyParser())
    filters.uses.forEach(function (func) {
      server.use(func)
    })

    actions.modules.forEach(function (mod) {
      mod.methods.forEach(function (meth) {
        let path = actions.path + mod.path + meth.path
        switch (meth.method) {
          case 'post':
            server.post({ path: path, version: meth.version }, meth.handler)
            break
          case 'get':
            server.get({ path: path, version: meth.version }, meth.handler)
            break
          case 'put':
            server.put({ path: path, version: meth.version }, meth.handler)
            break
          case 'del':
            server.del({ path: path, version: meth.version }, meth.handler)
            break
          default:
            break
        }
      })
    })
    server.listen(this.config.port, function () {
      console.log('服务启动，%s 正在监听 %s 端口', server.name, server.url)
    })
  }
}
